package com.yuanduo_app.bridge;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.IllegalViewOperationException;
import cn.ydxlm.vrlibrary.VRPlayerActivity;
import com.xujl.fastlib.base.BaseModule;
import com.xujl.fastlib.http.NetworkManager;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.task.Emitter;
import com.xujl.task.RxExecutor;
import com.xujl.task.Task;

import com.yuanduo_app.MainApplication;
import com.yuanduo_app.consts.BundleKey;
import com.yuanduo_app.event.CheckVersionEvent;
import com.yuanduo_app.route.ARouterUtils;
import com.yuanduo_app.utils.DeviceUtils;
import com.yuanduo_app.utils.MapUtils;
import com.yuanduo_app.utils.ViewHelper;

import org.greenrobot.eventbus.EventBus;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class RNBridgeModule extends BaseModule {
    private static final String TAG = "RNBridgeModule";

    public RNBridgeModule (ReactApplicationContext reactContext) {
        super(reactContext);
        LogS.i(TAG, "create");
    }

    //    重写getName方法声明Module类名称,在RN调用时用到
    @Override
    public String getName () {
        return "BridgeManager";
    }

    @ReactMethod
    public void initlizationBaseUrlString (String url) {
        LogS.i(TAG, "url:" + url);
        NetworkManager.getInstance().setDefaultUrl(url);
        EventBus.getDefault().post(new CheckVersionEvent(false));
    }

    //    声明的方法，外界调用
    @ReactMethod
    public void getAppVersion (Callback successCallback) {
        try {
            PackageInfo info = getPackageInfo();
            if (info != null) {
                successCallback.invoke(info.versionName);
            } else {
                successCallback.invoke("");
            }
        } catch (IllegalViewOperationException e) {
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void startActivity (String action) {
        startActivity(action, null);
    }

    @ReactMethod
    public void startActivity (String action, String paramsJson) {
        final Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(action);
        if (!StringUtils.isEmpty(paramsJson)) {
            final Bundle bundle = new Bundle();
            bundle.putString(BundleKey.DATA, paramsJson);
            intent.putExtras(bundle);
        }
        intent.setAction(action);
        MainApplication.getInstance().startActivity(intent);
    }

    @ReactMethod
    public void startRouteActivity (String route) {
        ARouterUtils.startActivity(route);
    }

    @ReactMethod
    public void getSystemInfo (Callback successCallback) {
        WritableMap map = new WritableNativeMap();
        map.putString("os", "android");//系统
        map.putString("ip", getIPAddress(MainApplication.getApplication()));//ip
        map.putString("model", android.os.Build.MODEL);//型号
        map.putString("brand", android.os.Build.BRAND);//厂商
        map.putString("sysVersionNum", Build.VERSION.RELEASE);//厂商
        map.putString("imei", getDeviceId(MainApplication.getApplication()));//手机识别码
        map.putString("appVersion", getPackageInfo().versionName);//应用版本号


        map.putString("deviceId", DeviceUtils.getAndroidID());
        map.putString("deviceBankId", DeviceUtils.getIMEI());

        map.putString("interIpAddress", DeviceUtils.getIPAddress());
        map.putString("Mac", DeviceUtils.getMacAddress());
        map.putString("simCardNumber", DeviceUtils.getPhoneNumber());
        map.putString("simCardNum", DeviceUtils.getSimNum());
        map.putString("deviceType", "1");
        map.putString("deviceName", DeviceUtils.getSystemModel());
        map.putString("appType", "android");

        RxExecutor.getInstance()
                .executeTask(new Task<String>() {
                    @Override
                    public void run (Emitter<String> emitter) throws Exception {
                        super.run(emitter);
                        emitter.next(DeviceUtils.getNetIp());
                    }

                    @Override
                    public void onNext (String ipAddress) {
                        super.onNext(ipAddress);
                        map.putString("ipAddress", ipAddress);
                        map.putString("ipVersion", DeviceUtils.getIpVType(ipAddress));
                        successCallback.invoke(map);
                    }
                });


    }

    //    获取 APP 信息
    @ReactMethod
    public PackageInfo getPackageInfo () {
        PackageManager manager = getReactApplicationContext().getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getReactApplicationContext().getPackageName(), 0);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return info;
        }
    }

    /**
     * 地图导航
     */
    @ReactMethod
    public void mapNavigation (double startLat, double startLon, double endLat, double endLon, String endName) {
        final double[] start = MapUtils.bdToGaoDe(startLat,
                startLon);
        final double[] end = MapUtils.bdToGaoDe(endLat
                , endLon);
        MapUtils.openGaoDeNavi(start[0], start[1], "", end[0], end[1]
                , endName);
    }

    /**
     * 获取底部导航栏高度
     *
     * @return
     */
    @ReactMethod
    public void getNavigationBarHeight (Callback callback) {
        callback.invoke(ViewHelper.getNavigationBarHeight(MainApplication.getApplication()));
    }

    public static String getDeviceId (Context context) {
        return Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
    }

    public static String getIPAddress (Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {    // 当前使用2G/3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {    // 当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());    // 得到IPV4地址
                return ipAddress;
            }
        } else {
            // 当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP (int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    @ReactMethod
    public void openVRPlayer (String url, String command) {
        final Intent intent = new Intent(MainApplication.getApplication(), VRPlayerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("url", url);
        MainApplication.getApplication().startActivity(intent);
    }

}